package com.tars.txtm.trasactional;

import com.alibaba.fastjson.JSONObject;
import com.tars.txtm.enums.TxEnum;
import com.tars.txtm.netty.NettyClient;
import com.tars.txtm.util.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: Franz 2022/3/19
 */
@Component
public class MyTransactionalManager {

    private static NettyClient client;

    private static Map<String,MyTransactional> txMap = new ConcurrentHashMap();

    private static ThreadLocal<String> threadTxGroupID = new ThreadLocal();

    @Autowired
    public void setClient(NettyClient client) {
        MyTransactionalManager.client = client;
    }

    public static String createTxGroupID() {
        String groupID = UUID.randomUUID().toString().replace("-", "");
        threadTxGroupID.set(groupID);
        return groupID;
    }

    public static String getCurrentTxGroupID() {
        return threadTxGroupID.get();
    }

    public static MyTransactional createTransaction(String txGroupID, int txCount) {
        MyTransactional transactional = new MyTransactional();
        transactional.setTxGroupID(txGroupID);
        transactional.setTxCount(txCount);
        transactional.setTask(new Task());
        txMap.put(threadTxGroupID.get(),transactional);
        return transactional;
    }

    public static void addTransaction(MyTransactional transactional, Boolean isEnd) {
        JSONObject msg = new JSONObject();
        msg.put("txGroupID", transactional.getTxGroupID());
        msg.put("status", transactional.getStatus().type);
        msg.put("txCount", transactional.getTxCount());
        msg.put("isEnd", isEnd);
        client.send(msg);
    }

    public static MyTransactional getCurrentThreadTX(String groupId) {
        return txMap.get(groupId);
    }

    public static void setCurrentTxGroupID(String txGroupID) {
        threadTxGroupID.set(txGroupID);
    }
}
